<template>
  <section class="todoapp">
    <hm-header @addList="addList"></hm-header>
    <hm-main
      :list="renderList"
      @del="del"
      @changeFlag="changeFlag"
      @changeAll="changeAll"
    ></hm-main>
    <hm-footer
      :sum="sum"
      :list="list"
      :isShowClear="isShowClear"
      @changeAll="changeAll"
      @clearAll='clearAll'
      :type="type"
      @changeType="changeType"
    ></hm-footer>
  </section>
</template>

<script>
import HmHeader from './components/hm-header.vue'
import HmMain from './components/hm-main.vue'
import HmFooter from './components/hm-footer.vue'
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  data() {
    return {
      // 这个list是原始的，完整的数据，给子组件传的数据，没必要是完整的数据
      // 给用户展示的，只需要是过滤后的数据即可 showList
      list: JSON.parse(localStorage.getItem('list')) || [
        { id: 1, value: '吃饭', flag: false },
        { id: 2, value: '睡觉', flag: true },
        { id: 3, value: '打豆豆', flag: false },
      ],
      type: 'all', // 过滤条件
    }
  },
  computed: {
    renderList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.flag)
        case 'completed':
          return this.list.filter((item) => item.flag)
        default:
          return this.list
      }
    },
    //计算剩余的未完成的数量
    sum() {
      return this.list.filter((item) => !item.flag).length
    },
//
    isShowClear() {
      return this.list.some((item) => item.flag === true)
    },
    // changeAll(){
    //   return this.list.every((item) =>item.flag === true)
    // }
  },
  methods: {

    //全选功能
    changeAll(flag) {
      // 让list中的所有的任务，和flag同步
      this.liat = this.list.forEach((item) => (item.flag = flag))
    },

    changeFlag(flag, id) {
      // 根据 id 找到数组中的对应项，进行更新 find
      const obj = this.list.find((item) => item.id === id)
      obj.flag = flag
    },

    //删除
    del(id) {
      const event = this.list.find((item) => item.id === id)
      if (!event.flag) return alert('未完成，不要删')
      this.list = this.list.filter((item) => item.id !== id)
    },

    //添加
    addList(value) {
      this.list = [{ id: +new Date(), value: value, flag: false }, ...this.list]
    },

    //删除完成
    clearAll() {
      //没有被勾选的留下来
      this.list = this.list.filter((item) => !item.flag)
    },
    //
    changeType(type){
      
      this.type=type
    }
  },
  watch: {
    list: {
      deep: true,
      handler(newValue) {
        // 存本地之前，先转 JSON
        localStorage.setItem('list', JSON.stringify(newValue))
      },
    },
  },
}
</script>

<style></style>
